"use strict";

var debug = require('debug')('district');
var redisCo = require('../../model/redis.js').redisCo;
var client = require('../../model/redis.js').client;
var redis = require('../../model/redis/district.js');

function DaoRedis() {
}
var dp = DaoRedis.prototype;
module.exports = new DaoRedis();

function __getKey(_id) {
    return 'district:' + _id;
}

dp.save = function*(district) {
    debug('save redis, input', district);
    yield redisCo.hmset(
        __getKey(district._id.toString()),
        //
        '_id', district._id,
        'adCode', district.adCode,
        'areaCode', district.areaCode,
        'cityCode', district.cityCode,
        'loc', district.loc.coordinates.join(','),
        'pId', district.pId,
        'subId', district.subId.join(','),
        'level', district.level,
        'name', district.name,
        'createdAt', district.createdAt,
        'updatedAt', district.updatedAt
    );
};

dp.hexists = function*(_id) {
    debug('hexists redis, input', _id);
    let result = yield redisCo.hexists(__getKey(_id));
    debug('hexists redis, output', result);
    return result;
};

dp.get = function*(_id) {
    debug('get redis,input' + _id);
    let isExists = this.hexists(_id);
    if (!isExists) {
        return null;
    }

    // result 是一个数组
    let result = yield redisCo.hmget(this.hexists(_id), ['_id', //1
        'adCode',
        'areaCode',
        'cityCode',
        'loc',

        'pId', // 6
        'subId',
        'level',
        'name',
        'createdAt',
        'updatedAt'
    ]);

    debug('get redis,mid', result);

    let obj = {
        _id: result[0], // 1
        adCode: result[1],
        areaCode: result[2],
        cityCode: result[3],
        loc: result[4],

        pId: result[5], // 6
        subId: result[6],
        level: result[7],
        name: result[8],
        createdAt: result[9],
        updatedAt: result[10]
    };
    debug('get redis,output' + obj);
    return obj;
};

dp.getByPid = function*(pId) {
    if (pId === null) {
        return null;
    }

    let parent = yield this.get(pId);
    if (!parent) {
        return null;
    }

    let result = [];
    for (let i = 0; i < parent.subId.length; i++) {
        let item = yield this.get(parent.subId[i]);
        if (!item) {
            return null;
        }
        result.push(item);
    }

    return result;
};

dp.testLua = function*() {
    client.myset(2, 'testing', 'superise');
};

dp.fun = function*() {
    client.fun(2, 'abc', 'ddd');
};

dp.add = function*() {
    client.add(2, 1111, 2222);
};

dp.distance = function*() {
    client.distance(4, 116.405285, 39.904989, 116.458605, 39.90511);
};